import com.mit.web.business.proxy.MaintenanceProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.util.FlexUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.util.Validator;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.vo.maintenance.FabricCatVO;

import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.controls.DataGrid;
import mx.controls.TextInput;
import mx.events.DataGridEvent;
import mx.events.DataGridEventReason;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;
import mx.utils.StringUtil;


private var _maintenanceProxy:MaintenanceProxy = MaintenanceProxy.getInstance();
[Bindable] private var _list:ArrayCollection = new ArrayCollection();
private var _logger:ILogger;
private var _pm:IProgressMonitor;

private function init():void{
	_logger = LogUtil.getLogger(this);
	doRetrieve();
}

private function doRetrieve():void{
	var responder:IInvokeResponder = _maintenanceProxy.getFabricCats().installProgressBar(_pm, this);	
	responder.addResultListener(retrieveListHandler);
	responder.addFaultListener(exceptionHandler);
}

private function retrieveListHandler(event:ResultEvent):void{
	_list = event.result as ArrayCollection;
	_logger.debug("_list: " + _list);
	for each (var o:Object in _list) {
		o.saveOriginal();
	}
	fabricCatDataGrid.validateNow();
}

private function doNew(event:MouseEvent):void{
	_list.addItem(new FabricCatVO()); 
	fabricCatDataGrid.validateNow();
	fabricCatDataGrid.editedItemPosition = {columnIndex:0, rowIndex:_list.length - 1};
}

private function doSave(event:MouseEvent):void{
	var cloneList:ArrayCollection = new ArrayCollection();
	cloneList = FlexUtil.deepClone(_list) as ArrayCollection;
	for each (var o:Object in cloneList) {
		if (o.id < 1 && (o.name == null || o.name == "")) {
			_list.removeItemAt(_list.getItemIndex(o));
		}	
	}
	fabricCatDataGrid.validateNow();
	
	//validation to privent duplicate record
  	if (!validate()) {
 	 	event.preventDefault();
  		return;
  	}
	
	// Update List
	var paramList:ArrayCollection = new ArrayCollection();
	for each (var o:Object in _list) {
		if (o.original == null) {
			// new fabric category
			_logger.debug("create fabric category: name=" + o.name);
			paramList.addItem(o);
		} else {
			// update fabric category
			if (o.name != o.original.name) {
				_logger.debug("fabric category: name=" + o.name + " will be updated");
				paramList.addItem(o);
			} else {
				_logger.debug("fabric category: name=" + o.name + " has no change");
			}
		}
	}
	
	//Save
 	if (paramList.length > 0) {
		var responder:IInvokeResponder = _maintenanceProxy.updateFabricCats(
			paramList).installProgressBar(_pm, this);
		responder.addResultListener(savedHandler);
		responder.addFaultListener(exceptionHandler);
	}
}

private function savedHandler(event:ResultEvent):void {
	retrieveListHandler(event);
	showMessageTip(ResourceManager.getInstance().getString(
		Constants.BUNDLE_COMMON,"info.common.saveOk"),  fabricCatDataGrid);
}

private function validate():Boolean{
	var cList:ArrayCollection = new ArrayCollection();
	cList = FlexUtil.deepClone(_list) as ArrayCollection;
	for each(var o:Object in _list){
		var name:String = o.name;
		
		var hasError:Boolean = false;
		var myError:String;
		
		if (name == null || name == "") {
			myError = ResourceManager.getInstance().getString(
				Constants.BUNDLE_COMMON,"error.common.requiredField");
			fabricCatDataGrid.editedItemPosition = {columnIndex:1, rowIndex:_list.getItemIndex(o)};
			hasError = true;
		}
		
		if (!hasError) {
			for each (var c:Object in cList) {
				//Error found! both are new item, how to handle?!
				if (name == c.name && cList.getItemIndex(c) 
						!= _list.getItemIndex(o)) {
					// duplicate name
					myError = ResourceManager.getInstance().getString(
						Constants.BUNDLE_COMMON,"error.common.duplicateKey",[name]);
					fabricCatDataGrid.editedItemPosition = {columnIndex:1, rowIndex:_list.getItemIndex(o)};
					hasError = true;
					break;
				}
			}
		}
		
		if (hasError) {
			showVerticalMiddleErrorTipAt(myError, fabricCatDataGrid);
			return false;
		}
	}
	return true;
}

